import sys
import compiler
import reg

def r():
    """Reads line from stdin and returns it without line feed."""
    i = sys.stdin.readline()
    return i[:-1]


# v for verbose
v = False

# fr for filereader
fr = False

# iterate over arguments
for arg in sys.argv:

    # verbose mode
    if arg == '-v':
        v = True

    # filereader
    if arg == '-f':
        fr = True

# --

if fr:
    sys.stdout.write('file name? ')
    fn = r()

    # ensure file validity
    while True:
        try:
            f = open(fn)
            f.close()
        except:
            sys.stdout.write('File not found.\n')
            sys.stdout.write('file name? ')
            fn = r()
        else:
            while True:

                sys.stdout.write('regex: ')
                regex = compiler.comp(r(), v)
                reg.p(regex)

                hits = reg.acceptfile(fn, regex, v)

                # for counting hit total
                nhits = 0

                # iterate over hits, find hits
                for hit in hits:
                    if hit[1] > 0:
                        sys.stdout.write('line ' + str(hit[0]) + ' (' + str(hit[1]) + '): ' + hit[2] + '\n')
                        nhits = nhits + hit[1]
                sys.stdout.write('A total of ' + str(nhits) + ' hits.\n')



# "default"
else:

    sys.stdout.write('regex: ')
    regex = compiler.comp(r(), v)
    reg.p(regex)

    while True:
        sys.stdout.write('string to match: ')
        match = r()
        print reg.accept(match, regex, v)
